package com.fangzhen.config;

import com.fangzhen.common.BaseResponse;
import com.fangzhen.common.OperateEnum;
import com.fangzhen.util.BaseResponseUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局包装处理
 *
 * @author : z_sz
 * @date : 2020-09-09
 **/
@RestControllerAdvice
public class GlobalPackHandler<T> implements ResponseBodyAdvice<T> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        //判断aClass是不是指定的MappingJackson2HttpMessageConverter类型
        return MappingJackson2HttpMessageConverter.class.isAssignableFrom(aClass);
    }

    @Override
    public T beforeBodyWrite(T body, MethodParameter methodParameter,
                             MediaType mediaType,
                             Class<? extends HttpMessageConverter<?>> aClass,
                             ServerHttpRequest serverHttpRequest,
                             ServerHttpResponse serverHttpResponse) {

        if(null == body) {
            return (T)BaseResponseUtil.success(OperateEnum.OPTION_SUCCESS);
        }

        // 系统发生异常执行 校验异常、自定义异常、系统异常
        if(body.getClass().equals(BaseResponse.class)) {
            return body;
        }

        // 写操作成功执行
        if(body.getClass().equals(OperateEnum.class)) {
            return (T)BaseResponseUtil.success((OperateEnum)body);
        }

        // 读操作成功
        return (T)BaseResponseUtil.success(OperateEnum.QUERY_SUCCESS,body);
    }
}
